from flask import Flask, render_template, request, jsonify
import mysql.connector
import discussio

app = Flask(__name__)

Answer=''
# 假设这是处理问题的函数
def discussio_main(question):
    # 假设discussio.main是一个处理account并返回结果的函数
    try:
        return discussio.main(question)
    except Exception as e:
        print(f"An error occurred: {e}")
        return "发生了一个错误，请重试。"

# 应用程序启动时建立数据库连接
db = mysql.connector.connect(
    host="127.0.0.1",
    user="root",
    password="123456",
    database="ai",
    charset='utf8'
)

@app.route('/', methods=['GET', 'POST'])
def sd():
    # 创建一个游标对象
    cursor = db.cursor()
    # 使用游标执行SQL查询
    cursor.execute("SELECT question FROM qa")
    # 获取查询结果
    results = cursor.fetchall()
    # 关闭游标
    cursor.close()
    # print(Answer)
    answer='p5'
    if request.method == 'POST':
        # 处理 POST 请求
        answer = post()
    # 处理POST请求
    Answer=answer
    print(Answer)
    return render_template("zhuye.html", data=results)


@app.route('/post', methods=['POST'])
def post():
    question = request.json.get('message')
    cursor1 = db.cursor()
    if question:
        answer = discussio_main(question)
        sql = "INSERT INTO qa (question) VALUES (%s)"
        cursor1.execute(sql, (question,))
        db.commit()
        cursor1.close()
        print(f"Answer from discussio_main: {answer}")
    else:
        print("No question provided")
    return jsonify({'answer':answer})





# 应用程序关闭时关闭数据库连接
if __name__ == '__main__':
    app.run(debug=True)
